package main

import (
    "fmt"
    "github.com/360EntSecGroup-Skylar/excelize/v2"
    "github.com/lxn/walk"
	. "github.com/lxn/walk/declarative"
	"strings"
    "io/ioutil"
    "log"
    "os"
    // "io"
	"time"
)

var fileList []os.FileInfo
var folderPath string

func listFiles(p string) {
    files, err := ioutil.ReadDir(p)
    if err != nil {
        log.Fatal(err)
    }
    /*for _, f := range files {
        fmt.Println(f.Name())		
    }*/
	fileList = files

	for _, f := range fileList {
        fmt.Println(f.Name())		
    }
}

type MyMainWindow struct {
	*walk.MainWindow
	edit *walk.TextEdit
	Oldwords  *walk.LineEdit
	Newords   *walk.LineEdit
}

func mainGui()  {
	var openAction, showAboutBoxAction  *walk.Action
	
	mw := &MyMainWindow{}
	err := MainWindow{
		AssignTo: &mw.MainWindow, //窗口重定向至mw，重定向后可由重定向变量控制控件
		Title:    "BOM批量修改工具",      //标题
		Icon:	  "./m.png",
		MenuItems: []MenuItem{
			Menu{
				Text: "文件夹",
				Items: []MenuItem{
					Action{
						AssignTo:    &openAction,
						Text:        "选择路径",
						Image:       "./open.png",
						Enabled:     Bind("enabledCB.Checked"),
						Visible:     Bind("!openHiddenCB.Checked"),
						Shortcut:    Shortcut{walk.ModControl, walk.KeyO},
						OnTriggered: mw.openAction_Triggered,
					},
					Separator{},
					Action{
						Text:        "退出",
						OnTriggered: func() { mw.Close() },
					},
				},
			},
			Menu{
				Text: "关于",
				Items: []MenuItem{
					Action{
						AssignTo:    &showAboutBoxAction,
						Text:        "关于",
						OnTriggered: mw.showAboutBoxAction_Triggered,
					},
				},
			},
		},
		MinSize: Size{300, 400},
		Size:     Size{300, 400},
		Layout:   VBox{}, //样式，纵向		
		Children: []Widget{ //控件组
			TextEdit{
				AssignTo: &mw.edit,
				VScroll: true,
			},
			Label{Text: "输入: "},
			LineEdit{
				AssignTo: &mw.Oldwords,
				Text:     "旧字符",
			},
			LineEdit{
				AssignTo: &mw.Newords,
				Text:     "新字符",
			},
			PushButton{
				Text:      "替换",
				OnClicked: mw.wordReplace, //点击事件响应函数
			},
		},
	}.Create() //创建

	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	mw.Run() //运行

}

func (mw *MyMainWindow) openAction_Triggered() {
	dlg := new(walk.FileDialog)
	dlg.Title = "选择文件"
	if ok, err := dlg.ShowBrowseFolder(mw); err != nil {
		return
	} else if !ok {
		return
	}
	//fmt.Println(dlg.FilePath)
	folderPath = dlg.FilePath

	listFiles(dlg.FilePath)
	mw.edit.SetText("文件名：\r\n") //通过重定向变量设置TextEdit的Text
	for _, f := range fileList {
        mw.edit.AppendText(f.Name())
		mw.edit.AppendText("\r\n")		
    }
}

func (mw *MyMainWindow) showAboutBoxAction_Triggered() {
	walk.MsgBox(mw, "关于", "批量修改BOM用，作者：bean", walk.MsgBoxIconInformation)
}

// func (mw *MyMainWindow) selectFile() {

// 	dlg := new(walk.FileDialog)
// 	dlg.Title = "选择文件"
// 	dlg.Filter = "可执行文件 (*.xls)|*.xlsx|所有文件 (*.*)|*.*"

// 	mw.edit.SetText("") //通过重定向变量设置TextEdit的Text
// 	if ok, err := dlg.ShowOpen(mw); err != nil {
// 		mw.edit.AppendText("Error : File Open\r\n")
// 		return
// 	} else if !ok {
// 		mw.edit.AppendText("Cancel\r\n")
// 		return
// 	}
// 	s := fmt.Sprintf("Select : %s\r\n", dlg.FilePath)
// 	mw.edit.AppendText(s)
// }

func (mw *MyMainWindow) wordReplace() {
	oldwords := mw.Oldwords.Text()
	newords := mw.Newords.Text()

	fmt.Println(oldwords)
	fmt.Println(newords)

	year := time.Now().Format("2006")
	month := time.Now().Format("01")
	day := time.Now().Format("02")

	currentDay := year+month+day
	fmt.Print(currentDay)

	err:=os.Mkdir(folderPath+"\\"+currentDay,os.ModePerm)
	if err!=nil{
		fmt.Println(err)
		mw.edit.AppendText("错误：创建文件夹失败或已存在！\r\n")
	}

	for _, f := range fileList {
		//fmt.Println(folderPath + "\\"+f.Name())	
		processExcel(folderPath, f.Name(), oldwords, newords, mw, currentDay)
    }
	mw.edit.AppendText("处理结束！！\r\n")
}

func processExcel(folderPath string, fName string, o string, n string, mw *MyMainWindow, currentDay string)  {

	var fileP string
	fileP = folderPath + "\\"+fName

	mw.edit.AppendText("处理文件：\r\n")
	mw.edit.AppendText(fileP)
	mw.edit.AppendText("\r\n")
	mw.edit.AppendText("... ...\r\n")

    f, err := excelize.OpenFile(fileP)
    if err != nil {
        fmt.Println(err)
		mw.edit.AppendText("错误：打开文件错误！\r\n")
        return
    }
    // 获取工作表中指定单元格的值
    // cell, err := f.GetCellValue("Sheet1", "B1")
    // if err != nil {
    //     fmt.Println(err)
    //     return
    // }
	// fmt.Println("here")
    // fmt.Println(cell)
    // 获取 Sheet1 上所有单元格
	
	for _, name := range f.GetSheetList() {
		fmt.Println(name)
		mw.edit.AppendText("工作表：\r\n")
		mw.edit.AppendText(name)
		mw.edit.AppendText("\r\n")
		result, err := f.SearchSheet(name, o)
		if err != nil {
			fmt.Println(err)
			mw.edit.AppendText("错误：未检索到！\r\n")
			return
		}
		for _, rc := range result {
			mw.edit.AppendText("匹配到：\r\n")
			mw.edit.AppendText(rc)
			mw.edit.AppendText("\r\n")
			f.SetCellValue(name, rc, n)
		}
		
		//fmt.Println(idx)
		// rows, err := f.GetRows(name)
		// if err != nil {
		// 	fmt.Println(err)
		// 	return
		// }
		// for _, row := range rows {
		// 	for _, colCell := range row {
		// 		fmt.Print(colCell, "\t")
		// 		fmt.Print(row)
		// 		fmt.Print(colCell)
		// 	}
		// 	fmt.Println()
		// }
	}
	// year := time.Now().Format("2006")
	// month := time.Now().Format("01")
	// day := time.Now().Format("02")

	// currentDay := year+month+day
	// fmt.Print(currentDay)
	idx := strings.Index(fName, ".")
	
	newName := fName[:idx] + "-"+currentDay + fName[idx:]
	q := folderPath+"\\"+currentDay+"\\"+newName
	fmt.Println(q)
	mw.edit.AppendText("保存新文件...\r\n")
	mw.edit.AppendText(q)
	mw.edit.AppendText("\r\n")
	f.SaveAs(q)
	mw.edit.AppendText("保存！\r\n")

}

func main() {

    mainGui()
    //listFiles()

}